
-- Terminate any and all connections to database before attempting to drop it

declare @databaseName varchar(128)
set @databaseName = '$(dbname)'

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'$(dbname)')
begin

DECLARE loop_name INSENSITIVE CURSOR FOR
  SELECT spid
   FROM master..sysprocesses
   WHERE dbid = DB_ID(@databaseName)

OPEN loop_name
DECLARE @conn_id SMALLINT
DECLARE @exec_str VARCHAR(255)
FETCH NEXT FROM loop_name INTO @conn_id
WHILE (@@fetch_status = 0)
  BEGIN
    SELECT @exec_str = 'KILL ' + CONVERT(VARCHAR(7), @conn_id)
    EXEC( @exec_str )
    FETCH NEXT FROM loop_name INTO @conn_id
  END
DEALLOCATE loop_name


-- NOTE: no single or double quotes around parameter
drop database $(dbname) 

end

GO